package com.podcstr.controller;

import com.podcstr.entity.Comment;
import com.podcstr.entity.Podcast;
import com.podcstr.qualifier.CurrentSession;
import com.podcstr.service.CommentService;
import com.podcstr.service.exception.ServiceException;
import com.podcstr.session.UserSession;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import java.util.List;

/**
 * @author azim
 * @since 6/2/13 
 */

@Named
@RequestScoped
public class CommentAndRatingController {

    private Comment comment;
    private FacesContext context;

    @EJB
    private CommentService commentService;

    @Inject
    @CurrentSession
    private UserSession userSession;

    @PostConstruct
    public void init() {

        context = FacesContext.getCurrentInstance();

        if (comment == null) {
            comment = new Comment();
        }
    }

    //Getters and setters methods

    public void setCommentService(CommentService commentService) {
        this.commentService = commentService;
    }

    public Comment getComment() {
        return comment;
    }

    public void setComment(Comment comment) {
        this.comment = comment;
    }


    //Other Required methods

    public String add(Podcast podcast) {

        if (userSession.getUser() != null) {

            if (comment != null) {

                try {

                    comment.setPodcast(podcast);
                    comment.setUser(userSession.getUser());
                    commentService.add(comment);
                } catch (ServiceException e) {
                    if (e.getViolations().size() != 0) {
                        context.addMessage(null, new FacesMessage(e.getViolations().toString()));
                    }
                    context.addMessage(null, new FacesMessage(e.getMessage()));
                }
            }
        } else {

            context.addMessage(null, new FacesMessage("You must be logged in to add comment."));
        }

        return null;
    }

    public List<Comment> show(long podcastId) {

        return commentService.findByPodcastId(podcastId);
    }
}
